// 石钟山记练习脚本
// ------------------------------------------------------------
// 本文件同时承担数据与逻辑两大职责：
//  1. 练习原文 & 题库数据（choice + translation）
//  2. DOM 交互：文章渲染、题目轮播、计时、交卷评分与结果展示
// ------------------------------------------------------------

/********************
 * 数据区
 *******************/
const articleContent = `<h2>《石钟山记》</h2>
<p>《水经》云："彭蠡之口有石钟山焉。"郦元以为<strong><u>下临深潭</u></strong>，微风鼓浪，水石相搏，声如洪钟。是说也，人常疑之。今以钟磬置水中，虽大风浪不能鸣也，而况石乎！至唐李渤始访其遗踪，得双石于潭上，<strong><u>扣而聆之</u></strong>，南声函胡，北音清越，<strong><u>桴止响腾</u></strong>，余韵徐歇。自以为得之矣。然是说也，余尤疑之。<strong>石之铿然有声者，所在皆是也，而此独以钟名，何哉？</strong></p>

<p>元丰七年六月丁丑，余自齐安舟行<strong><u>适临汝</u></strong>，而长子迈将赴饶之德兴尉，送之至湖口，<strong><u>因得观</u></strong>所谓石钟者。寺僧使小童持斧，于乱石间择其一二扣之，硿硿焉。余<strong><u>固笑而不信</u></strong>也。至暮夜月明，独与迈乘小舟，至绝壁下。大石侧立千尺，如猛兽奇鬼，森然欲搏人；而山上栖鹘，闻人声亦惊起，磔磔云霄间；又有若老人咳且笑于山谷中者，或曰此鹳鹤也。余方心动欲还，而大声发于水上，<strong><u>噌吰如钟鼓不绝</u></strong>。舟人大恐。徐而察之，则山下皆石穴罅，不知其浅深，微波入焉，涵澹澎湃而为此也。舟回至两山间，将入港口，<strong>有大石当中流，可坐百人，空中而多窍，与风水相吞吐，有窾坎镗鞳之声，与<u>向之</u>噌吰者相应，如乐作焉。</strong>因笑谓迈曰："汝识之乎？噌吰者，周景王之无射也；窾坎镗鞳者，魏庄子之歌钟也。古之人不余欺也！"</p>

<p>事不目见耳闻，而臆断其有无，可乎？郦元之所见闻，<strong><u>殆与余同</u></strong>，而言之不详；士大夫终不肯以小舟夜泊绝壁之下，故莫能知；而渔工水师虽知而不能言。此世所以不传也。<strong>而陋者<u>乃</u>以斧斤考击而求之，自以为得其实。</strong>余是以记之，盖叹郦元之简，而笑李渤之陋也。`;

// 每道选择题：text, options[4], answer(索引0-3)
const choiceQuestions = [
  {
    text: '1. 郦元以为<strong>下<u>临</u>深潭</strong>（    ）',
    options: ['A. 靠近', 'B. 面对', 'C. 来到', 'D. 从高处往低处看'],
    answer: 3
  },
  {
    text: '2. <strong><u>扣</u>而聆之</strong>（    ）',
    options: ['A. 敲击', 'B. 紧贴', 'C. 求教，探问', 'D. 叩头'],
    answer: 0
  },
  {
    text: '3. <strong>桴止响<u>腾</u></strong>（    ）',
    options: ['A. 奔跑', 'B. 翻动', 'C. 传播', 'D. 跳跃'],
    answer: 2
  },
  {
    text: '4. 余自齐安舟行<strong><u>适</u>临汝</strong>（    ）',
    options: ['A. 恰逢', 'B. 往，到', 'C. 适合', 'D. 女子出嫁'],
    answer: 1
  },
  {
    text: '5. <strong><u>因</u>得观</strong>所谓石钟者（    ）',
    options: ['A. 因而', 'B. 于是', 'C. 沿袭', 'D. 趁机'],
    answer: 0
  },
  {
    text: '6. 余<strong><u>固</u>笑而不信</strong>也（    ）',
    options: ['A. 本来', 'B. 确实', 'C. 仍然', 'D. 坚决'],
    answer: 1
  },
  {
    text: '7. <strong>噌吰如钟鼓不<u>绝</u></strong>（    ）',
    options: ['A. 横渡', 'B. 独一无二地', 'C. 断', 'D. 尽'],
    answer: 3
  },
  {
    text: '8. 与<strong><u>向</u>之噌吰</strong>者相应（    ）',
    options: ['A. 先前', 'B. 对着', 'C. 接近', 'D. 过去'],
    answer: 0
  },
  {
    text: '9. <strong><u>殆</u>与余同</strong>，而言之不详（    ）',
    options: ['A. 迷惑', 'B. 大概，恐怕', 'C. 危险', 'D. 几乎'],
    answer: 1
  },
  {
    text: '10. 而陋者<strong><u>乃</u></strong>以斧斤考击而求之（    ）',
    options: ['A. 竟然', 'B. 于是', 'C. 原来是', 'D. 才'],
    answer: 0
  }
];

// 翻译题：sourceText, refAnswer, explanation
const translationQuestions = [
  {
    text: '11. 翻译下列句子（每小题3分，共9分）',
    subQuestions: [
      {
        sourceText: '①<strong>石之铿然有声者，所在皆是也，而此独以钟名，何哉？</strong>',
        refAnswer: '敲击后能发出声响的石头，到处都有，可是唯独这座山用钟来命名，这是为什么呢？',
        explanation: '"<strong>是、名</strong>" —— 定语后置用法需指出。'
      },
      {
        sourceText: '②<strong>有大石当中流，可坐百人，空中而多窍，与风水相吞吐，有窾坎镗鞳之声，与向之噌吰者相应，如乐作焉。</strong>',
        refAnswer: '有块大石头挡在水流的中央，上面可坐百来个人，中间是空的而且有很多窟窿，风吹浪打、吞进吐出，发出物体相撞声和钟鼓齐鸣声，跟先前轰隆的声音互相应和，好像音乐演奏起来一样。',
        explanation: '"<strong>当、空中、向</strong>" 等关键词需得分。'
      },
      {
        sourceText: '③<strong>而陋者乃以斧斤考击而求之，自以为得其实。</strong>',
        refAnswer: '而浅陋的人竟用斧头敲打(山石)的办法来探求石钟山命名的原因，自认为得到了它的真相。',
        explanation: '注意"<strong>乃、考击、其实</strong>"等词义。'
      }
    ]
  }
];

/********************
 * 配置区
 *******************/
const TOTAL_TIME_SEC = 20 * 60; // 20 分钟
const CHOICE_POINT = 1;         // 每道选择题分值
const TRANS_POINT  = 3;         // 每道翻译小题分值

/********************
 * 状态变量
 *******************/
let currentIndex = 0; // 全题目线性索引
const questions = [...choiceQuestions, ...translationQuestions];
let userAnswers = new Array(questions.length).fill(null);
let translationScores = new Array(3).fill(null); // 三个翻译小题的自评分数
let timerId = null;
let remaining = TOTAL_TIME_SEC;

/********************
 * DOM 便捷函数
 *******************/
const $ = (id) => document.getElementById(id);

/********************
 * 初始化入口
 *******************/
window.addEventListener('DOMContentLoaded', () => {
  // 渲染文章
  $("article-content").innerHTML = articleContent;

  // 初始化总题数
  $("total-questions").innerText = questions.length;

  // 首题渲染
  renderQuestion();
  updateNavButtons();

  // 开启倒计时
  timerId = setInterval(() => {
    remaining--;
    if (remaining <= 0) {
      clearInterval(timerId);
      submitPaper();
    }
    renderTimer();
  }, 1000);
  renderTimer();
});

/********************
 * 渲染计时
 *******************/
function renderTimer() {
  const m = String(Math.floor(remaining / 60)).padStart(2, '0');
  const s = String(remaining % 60).padStart(2, '0');
  $("timer-display").innerText = `${m}:${s}`;
}

/********************
 * 题目渲染核心
 *******************/
function renderQuestion() {
  const q = questions[currentIndex];
  $("current-question").innerText = currentIndex + 1;

  // 判断题型
  const isChoice = currentIndex < choiceQuestions.length;
  const choiceBox = $("question-options");
  const transBox  = $("translation-question");

  if (isChoice) {
    $("question-text").innerHTML = q.text;

    // 清空并生成选项
    choiceBox.innerHTML = '';
    q.options.forEach((opt, idx) => {
      const optEl = document.createElement('div');
      optEl.className = 'question-option';
      optEl.innerHTML = `
        <label>
          <input type="radio" name="option" value="${idx}" ${userAnswers[currentIndex] === idx ? 'checked' : ''}>
          <span class="option-text">${opt}</span>
        </label>`;
      optEl.addEventListener('click', () => {
        const radio = optEl.querySelector('input[type="radio"]');
        radio.checked = true;
        userAnswers[currentIndex] = idx;
        
        // 清除其他选项的选中状态
        choiceBox.querySelectorAll('.question-option').forEach(el => {
          el.classList.remove('selected');
        });
        
        // 标记当前选项为选中
        optEl.classList.add('selected');
        updateNavButtons();
      });
      
      // 如果是当前选中的选项，添加选中样式
      if (userAnswers[currentIndex] === idx) {
        optEl.classList.add('selected');
      }
      
      choiceBox.appendChild(optEl);
    });

    choiceBox.classList.remove('hidden');
    transBox.classList.add('hidden');
  } else {
    // 翻译题（第11题）
    const trans = q;
    
    $("question-text").innerHTML = trans.text;
    
    // 创建翻译题的完整HTML结构
    transBox.innerHTML = `
      <div class="translation-comprehensive">
        ${trans.subQuestions.map((subQ, idx) => `
          <div class="translation-sub-question">
            <div class="translation-text">
              <strong>${subQ.sourceText}</strong>
            </div>
            
            <div class="translation-input-section">
              <h4>请翻译上述句子：</h4>
              <textarea 
                id="translation-input-${idx}" 
                class="translation-textarea" 
                placeholder="请在此输入你的翻译..."
                ${userAnswers[currentIndex] && userAnswers[currentIndex][idx] ? 'disabled' : ''}
              >${userAnswers[currentIndex] && userAnswers[currentIndex][idx] ? userAnswers[currentIndex][idx] : ''}</textarea>
            </div>
            
            <div class="translation-answer ${userAnswers[currentIndex] ? '' : 'hidden'}" id="translation-answer-${idx}">
              <h4>参考答案：</h4>
              <p class="reference-answer">${subQ.refAnswer}</p>
              <p><strong>解析：</strong><span>${subQ.explanation}</span></p>
              
              <div class="self-scoring-section">
                <h4>请根据参考答案为自己的翻译打分（0-3分）：</h4>
                <div class="score-options">
                  <label><input type="radio" name="self-score-${idx}" value="0" ${translationScores[idx] === 0 ? 'checked' : ''}> 0分</label>
                  <label><input type="radio" name="self-score-${idx}" value="1" ${translationScores[idx] === 1 ? 'checked' : ''}> 1分</label>
                  <label><input type="radio" name="self-score-${idx}" value="2" ${translationScores[idx] === 2 ? 'checked' : ''}> 2分</label>
                  <label><input type="radio" name="self-score-${idx}" value="3" ${translationScores[idx] === 3 ? 'checked' : ''}> 3分</label>
                </div>
              </div>
            </div>
          </div>
        `).join('')}
        
        <div class="translation-submit-section ${userAnswers[currentIndex] ? 'hidden' : ''}">
          <button 
            id="submit-all-translations" 
            class="submit-translation-btn"
            onclick="submitAllTranslations()"
          >
            提交所有翻译
          </button>
        </div>
      </div>
    `;
    
    // 为自评分添加事件监听
    if (userAnswers[currentIndex]) {
      trans.subQuestions.forEach((_, idx) => {
        const scoreInputs = transBox.querySelectorAll(`input[name="self-score-${idx}"]`);
        scoreInputs.forEach(input => {
          input.addEventListener('change', (e) => {
            translationScores[idx] = parseInt(e.target.value);
            updateNavButtons();
          });
        });
      });
    }

    choiceBox.classList.add('hidden');
    transBox.classList.remove('hidden');
  }
}

/********************
 * 导航函数
 *******************/
function prevQuestion() {
  if (currentIndex > 0) {
    currentIndex--;
    renderQuestion();
    updateNavButtons();
  }
}

function nextQuestion() {
  if (currentIndex < questions.length - 1) {
    currentIndex++;
    renderQuestion();
    updateNavButtons();
  }
}

/********************
 * 导航按钮更新
 *******************/
function updateNavButtons() {
  const prevBtn = $("prev-btn");
  const nextBtn = $("next-btn");
  const submitBtn = $("submit-test-btn");

  // 上一题按钮
  prevBtn.disabled = (currentIndex === 0);

  // 判断当前题是否已完成
  let currentCompleted = false;
  
  if (currentIndex < choiceQuestions.length) {
    // 选择题：检查是否已选择答案
    currentCompleted = userAnswers[currentIndex] !== undefined;
  } else {
    // 翻译题：检查是否已提交答案并完成所有自评分
    currentCompleted = userAnswers[currentIndex] !== undefined && 
                      translationScores.every(score => score !== undefined && score !== null);
  }

  // 下一题按钮
  if (currentIndex === questions.length - 1) {
    nextBtn.style.display = "none";
    submitBtn.style.display = currentCompleted ? "inline-block" : "none";
  } else {
    nextBtn.style.display = "inline-block";
    nextBtn.disabled = !currentCompleted;
    submitBtn.style.display = "none";
  }
}

/********************
 * 结果计算
 *******************/
function calculateResults() {
  let choiceScore = 0;
  let translationScore = 0;
  
  // 计算选择题得分
  for (let i = 0; i < choiceQuestions.length; i++) {
    if (userAnswers[i] === choiceQuestions[i].answer) {
      choiceScore += CHOICE_POINT;
    }
  }
  
  // 计算翻译题得分（使用自评分）
  for (let i = 0; i < 3; i++) {
    if (translationScores[i] !== undefined && translationScores[i] !== null) {
      translationScore += translationScores[i];
    }
  }
  
  const totalScore = choiceScore + translationScore;
  const maxScore = choiceQuestions.length * CHOICE_POINT + 3 * TRANS_POINT;
  
  return {
    choiceScore,
    translationScore,
    totalScore,
    maxScore,
    percentage: Math.round((totalScore / maxScore) * 100)
  };
}

/********************
 * 计分 & 结果页
 *******************/
function submitPaper() {
  clearInterval(timerId);

  // 计算得分
  const results = calculateResults();

  // 更新结果页
  $("score-percentage").innerText   = `${results.percentage}%`;
  $("total-score").innerText        = results.totalScore;
  $("max-score").innerText          = results.maxScore;
  $("choice-score").innerText       = results.choiceScore;
  $("choice-max").innerText         = choiceQuestions.length * CHOICE_POINT;
  $("translation-score").innerText  = results.translationScore;
  $("translation-max").innerText    = 3 * TRANS_POINT;

  // 详细错题列表
  const detailBox = $("result-details");
  detailBox.innerHTML = '';
  
  // 选择题结果
  choiceQuestions.forEach((q, idx) => {
    const div = document.createElement('div');
    const correct = q.options[q.answer].slice(0, 1); // A/B/C...
    const user = userAnswers[idx] == null ? '未作答' : q.options[userAnswers[idx]].slice(0,1);
    div.innerHTML = `<p><strong>第${idx + 1}题：</strong>${q.text.replace(/（.*?）/, '')} —— 正确答案：<strong>${correct}</strong>，你的答案：<strong>${user}</strong></p>`;
    if (correct !== user) div.classList.add('wrong');
    detailBox.appendChild(div);
  });
  
  // 翻译题结果
  if (translationQuestions.length > 0) {
    const q = translationQuestions[0];
    const questionIndex = choiceQuestions.length + 1;
    
    q.subQuestions.forEach((subQ, idx) => {
      const div = document.createElement('div');
      const userAnswer = userAnswers[choiceQuestions.length] && userAnswers[choiceQuestions.length][idx] ? userAnswers[choiceQuestions.length][idx] : '未作答';
      const selfScore = translationScores[idx] !== undefined && translationScores[idx] !== null ? translationScores[idx] : '未评分';
      
      div.innerHTML = `
        <div class="translation-result">
          <p><strong>第${questionIndex}题第${idx + 1}小题（翻译题）：</strong>${subQ.sourceText}</p>
          <p><strong>你的翻译：</strong>${userAnswer}</p>
          <p><strong>参考答案：</strong>${subQ.refAnswer}</p>
          <p><strong>自评分：</strong>${selfScore} / ${TRANS_POINT} 分</p>
        </div>
      `;
      div.classList.add('translation-result-item');
      detailBox.appendChild(div);
    });
  }

  // 切换显示
  $("practice-layout").classList.add('hidden');
  $("practice-result").classList.remove('hidden');
}

/********************
 * 其它控制
 *******************/
function retryTest() {
  // 重置状态
  currentIndex = 0;
  userAnswers.fill(null);
  translationScores.fill(null); // 重置翻译题自评分
  remaining = TOTAL_TIME_SEC;
  $("practice-result").classList.add('hidden');
  $("practice-layout").classList.remove('hidden');
  renderQuestion();
  updateNavButtons();
  timerId = setInterval(() => {
    remaining--;
    if (remaining <= 0) {
      clearInterval(timerId);
      submitPaper();
    }
    renderTimer();
  }, 1000);
  renderTimer();
}

function goBack() {
  window.history.back();
}

function goHome() {
  window.location.href = '/';
}

// 提交所有翻译答案的函数
function submitAllTranslations() {
  const trans = questions[currentIndex];
  const userTranslations = [];
  let hasEmptyAnswer = false;
  
  // 检查所有翻译是否都已填写
  for (let i = 0; i < 3; i++) {
    const textarea = $(`translation-input-${i}`);
    if (textarea.value.trim() === '') {
      hasEmptyAnswer = true;
      break;
    }
    userTranslations.push(textarea.value.trim());
  }
  
  if (hasEmptyAnswer) {
    alert('请完成所有翻译题后再提交！');
    return;
  }
  
  // 保存用户答案
  userAnswers[currentIndex] = userTranslations;
  
  // 禁用所有文本框和提交按钮
  for (let i = 0; i < 3; i++) {
    const textarea = $(`translation-input-${i}`);
    const answerSection = $(`translation-answer-${i}`);
    
    textarea.disabled = true;
    answerSection.classList.remove('hidden');
  }
  
  // 隐藏提交按钮
  $('submit-all-translations').style.display = 'none';
  
  // 为自评分添加事件监听
  trans.subQuestions.forEach((_, idx) => {
    const scoreInputs = document.querySelectorAll(`input[name="self-score-${idx}"]`);
    scoreInputs.forEach(input => {
      input.addEventListener('change', (e) => {
        translationScores[idx] = parseInt(e.target.value);
        updateNavButtons();
      });
    });
  });
  
  updateNavButtons();
}
